// https://www.lintcode.com/problem/find-bottom-left-tree-value/description

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

// O(n)
// 法一：BFS
// class Solution {
// public:
//     /**
//      * @param root: a root of tree
//      * @return: return a integer
//      */
//     int findBottomLeftValue(TreeNode * root) {
//         queue<TreeNode*> q;
//         q.push(root);
//         int ans = root->val;
//         while (!q.empty())
//         {
//             int len = q.size();
//             ans = q.front()->val;
//             for (int i = 0; i < len; ++i) {
//                 TreeNode * tmp = q.front();
//                 q.pop();
//                 if (tmp->left) q.push(tmp->left);
//                 if (tmp->right) q.push(tmp->right);
//             }
//         }
//         return ans;
//     }
// };



// 法二：DFS O(n)
class Solution {
public:
    /**
     * @param root: a root of tree
     * @return: return a integer
     */
    int dfs(TreeNode * root, int depth, int& maxDepth, int& ans) { //注意maxDepth和ans都要引用
        if (depth > maxDepth) {
            maxDepth = depth;
            ans = root->val;
        }
        if (root->left) {
            dfs(root->left, depth + 1, maxDepth, ans);
        }
        if (root->right) {
            dfs(root->right, depth + 1, maxDepth, ans);
        }
        return ans;
    }
    int findBottomLeftValue(TreeNode * root) {
        int depth = 1;
        return dfs(root, 1, depth, root->val); //需要引用的不能传值
    }
};